<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/6
 * Time: 13:29
 */

namespace App\Http\Middleware;

use Closure;

class CheckAdminLogin
{


    public function handle($request, Closure $next)
    {
        if (!(is_login() && session('menus'))) {
            return redirect(urlAdmin('login', 'getIndex'));
        }
        // 是否是超级管理员
        if (!is_administrator()) {
            if (!empty(C('ADMIN_ALLOW_IP'))) {
                // 检查IP地址访问
                if (!in_array(request()->getClientIp(), explode(',', C('ADMIN_ALLOW_IP')))) {
                    return $this->dealResult('禁止访问！');
                }
            }
            //当前url
            $url = str_replace(request()->route()->getPrefix() . '/', '', '/' . request()->getRelativeUriForPath(request()->path()));
            if (!strpos($url, '/')) {
                $url .= '/index'; //补齐被浏览器忽略掉的index
            }
            //二级菜单权限检查
            if (!array_intersect([$url], session('menus.rules'))) {
                if (!in_array($url,['admin/edit-password','admin/edit-nickname','shop/charge-notify'])) {
                   return $this->dealResult('未授权访问！');
                }
            }
        }
        return $next($request);
    }

    public function dealResult($msg)
    {
        if (request()->ajax()) {
            return error($msg);
        } else {
            abort(503, $msg);
        }
    }

}

